﻿Public Class TimeEdit

	Public Event TimeChanged(sender As Object)

	Private _enteredTime As TimeSpan
	Public Property EnteredTime As TimeSpan
		Get
			Return _enteredTime
		End Get
		Set(ByVal Value As TimeSpan)
			_enteredTime = Value
			RaiseEvent TimeChanged(Me)
		End Set
	End Property

	Public Sub FocusEdit()
		txtTime.Focus()
	End Sub

	Private Sub TxtTime_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtTime.KeyDown
		Dim needToHide As Boolean
		If e.KeyCode = Keys.Enter Then
			needToHide = True
			EnteredTime = GetTimeFromString(txtTime.Text)


		ElseIf e.KeyCode = Keys.Escape Then
			needToHide = True

		End If

		If needToHide Then
			e.SuppressKeyPress = True
			e.Handled = True
			Me.Hide()
		End If

	End Sub


	Private Shared SecondsPerUnit As Dictionary(Of Char, Integer) = GetTimeUnits()
	Private Shared Function GetTimeUnits() As Dictionary(Of Char, Integer)
		Dim retUnitsDic As New Dictionary(Of Char, Integer)(5)
		With retUnitsDic
			.Add("s"c, 1)
			.Add("m"c, 60)
			.Add("h"c, 3600)
			'.Add("d"c, 86400)
			'.Add("w"c, 604800)
		End With

		Return retUnitsDic
	End Function


	Private Function GetTimeFromString(ByVal timeString As String) As TimeSpan
		Try

			If timeString.Contains(":") Then
				Return TimeSpan.Parse(timeString)
			End If

			Dim numberBuffer As String = String.Empty
			Dim totalSec As Long = 0
			Dim keyFound As Boolean = False
			For Each currentKey As Char In timeString

				If Char.IsNumber(currentKey) Then
					numberBuffer &= currentKey

				ElseIf SecondsPerUnit.ContainsKey(currentKey) Then
					totalSec += CInt(numberBuffer) * SecondsPerUnit(currentKey)
					numberBuffer = String.Empty
					keyFound = True

				End If

			Next

			'Assume it's minute 
			If Not keyFound Then totalSec = CInt(numberBuffer) * 60

			Return TimeSpan.FromSeconds(totalSec)

		Catch ex As Exception
			MessageBox.Show("Couldn't recognise the format.", "Please use 1:10:12 or ""1h20m45s"", ""3h""", MessageBoxButtons.OK)

		End Try

	End Function

End Class
